package com.ubtechinc.cruzr.launcher2;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.ubtechinc.cruzr.launcher2.adapter.NestAdapter;
import com.ubtechinc.cruzr.launcher2.callback.RxTimerListener;
import com.ubtechinc.cruzr.launcher2.model.helper.ClockHelper;
import com.ubtechinc.cruzr.launcher2.model.helper.ThirdStateHelper;
import com.ubtechinc.cruzr.launcher2.presenter.AppPresenter;
import com.ubtechinc.cruzr.launcher2.utlis.LogUtils;
import com.ubtechinc.cruzr.launcher2.utlis.RxTimer;
import com.ubtechinc.cruzr.launcher2.utlis.UbtCantans;
import com.ubtechinc.cruzr.launcher2.view.AppView;
import com.ubtechinc.cruzr.launcher2.widget.ClockView;
import com.ubtechinc.cruzr.launcher2.widget.DividerGridItemDecoration;
import com.ubtechinc.cruzr.launcher2.widget.HorizontalPageLayoutManager;
import com.ubtechinc.cruzr.launcher2.widget.PageIndicate;
import com.ubtechinc.cruzr.launcher2.widget.PageRecycleView;
import com.ubtechinc.cruzr.launcher2.widget.ThirdAppBar;
import com.ubtechinc.cruzr.userverify.api.CruzrSecurityApi;

import java.util.Calendar;

public class MainActivity extends Activity implements AppView, PageRecycleView.onPageChangeListener {

    private AppPresenter mAppPresenter;
    private PageRecycleView mRecyclerView;
    private NestAdapter mAdapter;
    private HorizontalPageLayoutManager gridLayoutManager;
    private int mLastX, mLastY;
    private boolean isDeleted = false;
    private PageIndicate mIndicate;
    private ThirdAppBar mBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LogUtils.e("launcher onCreate");
        mAppPresenter = new AppPresenter(this);
        initView();
        register();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(CruzrSecurityApi.get().getPassword())) {
            Intent intent = new Intent("com.ubt.cruzr.showbar");
            sendBroadcast(intent);//回到主界面显示导航条
        }
        LogUtils.e("launcher onResume");
        mAppPresenter.updateBattery();
        onDateTimeChange();
        if (UbtCantans.DATA_CHANGE) {
            mAppPresenter.reLoadApp();
        }
        if (mAppPresenter.isThirdStatus()) {
            LogUtils.e("remove third app status");
            ThirdStateHelper.removeThirdAppTask(LauncherApplication.getContext());
            mAppPresenter.removeThirdAppStatus();
            mBar.hide();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(BroadcastRec);
        unregisterReceiver(BroadcastKeybroad);
    }

    private void initView() {
        mBar = new ThirdAppBar();
        mBar.initShowBar(LauncherApplication.getContext(), R.layout.thirdapp_windown);
        mRecyclerView = (PageRecycleView) findViewById(R.id.id_recyclerview);
        mIndicate = (PageIndicate) findViewById(R.id.indicate);
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration());
        mRecyclerView.setOnPageChangeListener(this);
        initLayoutManager();
        mBar.setOnWindowClick(new ThirdAppBar.onWindowClick() {
            @Override
            public void onClose() {
                mBar.hide();
                ThirdStateHelper.removeThirdAppTask(LauncherApplication.getContext());
                mAppPresenter.removeThirdAppStatus();
            }
        });
        mBar.hide();
    }

    private void initLayoutManager() {
        gridLayoutManager = new HorizontalPageLayoutManager(UbtCantans.RECYCLE_ROWS, UbtCantans.RECYCLE_COLUMNS);
        mRecyclerView.setLayoutManager(gridLayoutManager);
    }

    @Override
    public void onPageChange(int curpage, int totalpage) {
        LogUtils.e("onpagechage = " + curpage + " total = " + totalpage);
        mAppPresenter.startItemAnimation(gridLayoutManager, mAdapter, curpage);
        mIndicate.reFreshPage(this, curpage, totalpage);
    }

    @Override
    public void onAppChange() {
        LogUtils.e("rqh onAppChange " + mAdapter);
        if (mAdapter != null) {
            UbtCantans.DATA_CHANGE = false;
            mAdapter.setList(mAppPresenter);
            LogUtils.e("rqh page info " + mRecyclerView.getPageIndex() + "  " + mAdapter.getPageCount());
            if (mRecyclerView.getPageIndex() >= mAdapter.getPageCount()) {
                mRecyclerView.setCurrentPage(0);
                onPageChange(0, mAdapter.getPageCount());
            } else {
                onPageChange(mRecyclerView.getPageIndex(), mAdapter.getPageCount());
            }
            mRecyclerView.snopPageQuick();
            mAdapter.notifyDataSetChanged();
        } else {
            onAppInit();
        }
        //**解决应用图标重复问题，这个方法为临时解决方案，需要优化**//
        final RxTimer timer = new RxTimer();
        timer.startTime(new RxTimerListener() {
            @Override
            public void onTimeNext() {
                timer.closeTimer();
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
            }
        }, 200, 200);
    }

    @Override
    public void onAppInit() {
        LogUtils.e("rqh onAppInit");
        UbtCantans.DATA_CHANGE = false;
        mAdapter = new NestAdapter(getApplicationContext(), mAppPresenter);
        mRecyclerView.setAdapter(mAdapter);
        onPageChange(0, mAdapter.getPageCount());
        mAppPresenter.updateBattery();
        mAppPresenter.startUpdateTime();
    }

    @Override
    public void onBatteryUpdate(String battery) {
        if (gridLayoutManager != null && mAdapter != null) {
            View view = gridLayoutManager.findViewByPosition(mAdapter.getPowerIndex());
            if (view != null) {
                TextView tx = (TextView) view.findViewById(R.id.powerdegress);
                if (tx != null) {
                    tx.setText(battery);
                }
            }
        }
    }

    @Override
    public void onDateTimeChange() {
        if (gridLayoutManager != null & mAdapter != null) {
            View view = gridLayoutManager.findViewByPosition(mAdapter.getClockIndex());
            if (view != null) {
                TextView tx1 = (TextView) view.findViewById(R.id.showtime);
                TextView tx2 = (TextView) view.findViewById(R.id.showdate);
                TextView tx3 = (TextView) view.findViewById(R.id.showweek);
                ClockHelper.updateTimeDegree(tx1, tx2, tx3);
                ClockView clockView = (ClockView) view.findViewById(R.id.clock);
                if (clockView != null) {
                    final Calendar now = Calendar.getInstance();
                    String id = now.getTimeZone().getID();
                    clockView.setTimeZoneId(id);
                }
            }
        }
    }

    @Override
    public void onStartDeleteState() {
        mAppPresenter.startItemAnimation(gridLayoutManager, mAdapter, mRecyclerView.getPageIndex());
    }

    @Override
    public void onStopDeleteState() {
        mAppPresenter.stopItemAnimation();
        mAppPresenter.enableDeleteState(false);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onThirdAppOpen() {
        mBar.show();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isDeleted = mAppPresenter.isAppDeleteState();
                mLastX = (int) event.getX();
                mLastY = (int) event.getY();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                int x = (int) event.getX();
                int y = (int) event.getY();
                int distancex = x - mLastX;
                int distancey = y - mLastY;
                if (Math.abs(distancex) < 5 && Math.abs(distancey) < 5) {
                    mAppPresenter.exitDeleteState(isDeleted);
                }
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }

    private void register() {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(UbtCantans.KEYBROAD_CHANGE);
        intentFilter.addAction(UbtCantans.RESET_NAVIGATION_BAR);
        intentFilter.addDataScheme("package");
        registerReceiver(BroadcastRec, intentFilter);
        IntentFilter intentFilter1 = new IntentFilter(UbtCantans.KEYBROAD_CHANGE);
        intentFilter1.addAction(UbtCantans.KEYBROAD_CHANGE);
        registerReceiver(BroadcastKeybroad, intentFilter1);
    }

    public final BroadcastReceiver BroadcastRec = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            LogUtils.e("收到的广播  = " + intent.getAction());
            if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) || Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
                mAppPresenter.reLoadApp();
            }
        }
    };
    public final BroadcastReceiver BroadcastKeybroad = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (UbtCantans.RESET_NAVIGATION_BAR.equals(intent.getAction())) {
                mBar.recoverView();
            } else if (UbtCantans.KEYBROAD_CHANGE.equals(intent.getAction())) {
                mBar.refreshView();
            }
        }
    };

    public void onclick(View v) {
        Intent intent = new Intent(this, LauncherSettingActivity.class);
        startActivity(intent);
//        mAdapter.notifyDataSetChanged();
    }
}
